'use strict';
const { Controller } = require('egg');

class WeappController extends Controller {
  // 登陆
  async login() {
    const { ctx, app } = this;
    const input = ctx.validate(ctx.request.body, {
      code: 'required|string',
    });

    if (app.config.pcenter && app.config.pcenter.secret) {
      const { token, user } = await ctx.service.weapp.plogin(input.code);
      ctx.success({
        user,
        token,
      }, '登录成功');
    } else {
      // 获取用户
      const user = await this.service.weapp.login(input.code);
      // 签名
      const token = app.jwt.sign({ userId: user._id }, app.config.key);
      ctx.success({
        user,
        token,
      }, '登录成功');
    }
  }
  // 授权
  async auth() {
    const { ctx } = this;
    const input = ctx.validate(ctx.request.body, {
      encryptedData: 'required|string',
      iv: 'required|string',
    });
    const user = await ctx.service.weapp.auth(ctx.weappUser, input.encryptedData, input.iv);
    this.ctx.success(user);
  }
  // 用户
  async me() {
    const { ctx } = this;
    const weappUser = ctx.weappUser;
    ctx.success(weappUser);
  }
}

module.exports = WeappController;
